// 棋盘配置
const BOARD_SIZE = 510;
const GRID_SIZE = 56;
const PIECE_RADIUS = 24;

// 初始FEN字符串
const INITIAL_FEN = "rnbakabnr/9/1c5c1/p1p1p1p1p/9/9/P1P1P1P1P/1C5C1/9/RNBAKABNR w - - 0 1";

// 棋子Unicode字符
const PIECES = {
    'r': '车', 'R': '俥', 
    'n': '马', 'N': '傌', 
    'b': '相', 'B': '象', 
    'a': '仕', 'A': '士', 
    'k': '帅', 'K': '将', 
    'c': '炮', 'C': '砲', 
    'p': '兵', 'P': '卒'
};

// 棋子颜色
const RED = 'red';
const BLACK = 'black';

// 游戏状态
let gameState = {
    fen: INITIAL_FEN,
    board: [],
    currentPlayer: 'w',
    selectedPiece: null,
    moveHistory: [],
    gameOver: false
};

// 初始化
document.addEventListener('DOMContentLoaded', () => {
    const canvas = document.getElementById('chessboard');
    canvas.addEventListener('click', handleCanvasClick);
    
    document.getElementById('new-game').addEventListener('click', startNewGame);
    document.getElementById('undo').addEventListener('click', undoMove);
    document.getElementById('ai-move').addEventListener('click', requestAIMove);
    
    startNewGame();
    
    // 初始显示FEN
    updateFenDisplay();
});

function startNewGame() {
    // 重置游戏状态
    gameState = {
        fen: INITIAL_FEN,
        board: parseFen(INITIAL_FEN),
        currentPlayer: 'w',
        selectedPiece: null,
        moveHistory: [],
        gameOver: false
    };
    
    // 重置引擎
    fetch('/reset_engine', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        }
    });
    
    updateGameDisplay();
    updateStatusDisplay();
    
    const moveList = document.getElementById('move-list');
    moveList.innerHTML = '';
}

function parseFen(fen) {
    const parts = fen.split(' ');
    const boardPart = parts[0];
    const rows = boardPart.split('/');
    
    const board = Array(10).fill().map(() => Array(9).fill(null));
    
    for (let row = 0; row < 10; row++) {
        let col = 0;
        for (let i = 0; i < rows[row].length; i++) {
            const char = rows[row][i];
            if (/[1-9]/.test(char)) {
                col += parseInt(char);
            } else {
                board[row][col] = {
                    type: char,
                    color: char === char.toUpperCase() ? RED : BLACK
                };
                col++;
            }
        }
    }
    
    return board;
}

function drawBoard() {
    const canvas = document.getElementById('chessboard');
    const ctx = canvas.getContext('2d');
    
    // 清除画布
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    
    // 绘制棋盘背景
    ctx.fillStyle = '#e8c58c';
    ctx.fillRect(0, 0, canvas.width, canvas.height);
    
    // 绘制网格线
    ctx.strokeStyle = '#000';
    ctx.lineWidth = 1;
    
    // 绘制横线
    for (let i = 0; i < 10; i++) {
        ctx.beginPath();
        ctx.moveTo(25, 25 + i * GRID_SIZE);
        ctx.lineTo(25 + 8 * GRID_SIZE, 25 + i * GRID_SIZE);
        ctx.stroke();
    }
    
    // 绘制竖线
    for (let i = 0; i < 9; i++) {
        // 上半部分
        ctx.beginPath();
        ctx.moveTo(25 + i * GRID_SIZE, 25);
        ctx.lineTo(25 + i * GRID_SIZE, 25 + 4 * GRID_SIZE);
        ctx.stroke();
        
        // 下半部分
        ctx.beginPath();
        ctx.moveTo(25 + i * GRID_SIZE, 25 + 5 * GRID_SIZE);
        ctx.lineTo(25 + i * GRID_SIZE, 25 + 9 * GRID_SIZE);
        ctx.stroke();
    }
    
    // 绘制九宫格
    ctx.beginPath();
    // 上半部分九宫斜线
    ctx.moveTo(25 + 3 * GRID_SIZE, 25);
    ctx.lineTo(25 + 5 * GRID_SIZE, 25 + 2 * GRID_SIZE);
    ctx.stroke();
    
    ctx.beginPath();
    ctx.moveTo(25 + 5 * GRID_SIZE, 25);
    ctx.lineTo(25 + 3 * GRID_SIZE, 25 + 2 * GRID_SIZE);
    ctx.stroke();
    
    // 下半部分九宫斜线
    ctx.beginPath();
    ctx.moveTo(25 + 3 * GRID_SIZE, 25 + 7 * GRID_SIZE);
    ctx.lineTo(25 + 5 * GRID_SIZE, 25 + 9 * GRID_SIZE);
    ctx.stroke();
    
    ctx.beginPath();
    ctx.moveTo(25 + 5 * GRID_SIZE, 25 + 7 * GRID_SIZE);
    ctx.lineTo(25 + 3 * GRID_SIZE, 25 + 9 * GRID_SIZE);
    ctx.stroke();
    
    // 绘制楚河汉界
    ctx.fillStyle = '#8c531b';
    ctx.font = 'bold 30px KaiTi, STKaiti, serif';
    ctx.textAlign = 'center';
    ctx.fillText('楚 河        汉 界', BOARD_SIZE / 2, 25 + 4.5 * GRID_SIZE);
    
    // 绘制棋子
    for (let row = 0; row < 10; row++) {
        for (let col = 0; col < 9; col++) {
            const piece = gameState.board[row][col];
            if (piece) {
                drawPiece(ctx, row, col, piece.type, piece.color);
            }
        }
    }
    
    // 如果有选中的棋子，绘制选中效果
    if (gameState.selectedPiece) {
        const { row, col } = gameState.selectedPiece;
        ctx.strokeStyle = '#00ff00';
        ctx.lineWidth = 3;
        ctx.beginPath();
        ctx.arc(25 + col * GRID_SIZE, 25 + row * GRID_SIZE, PIECE_RADIUS + 2, 0, Math.PI * 2);
        ctx.stroke();
    }
}

function drawPiece(ctx, row, col, type, color) {
    const x = 25 + col * GRID_SIZE;
    const y = 25 + row * GRID_SIZE;
    
    // 绘制棋子背景
    ctx.beginPath();
    ctx.arc(x, y, PIECE_RADIUS, 0, Math.PI * 2);
    ctx.fillStyle = color === RED ? '#f44336' : '#222';
    ctx.fill();
    
    // 绘制棋子边框
    ctx.strokeStyle = '#fff';
    ctx.lineWidth = 1;
    ctx.stroke();
    
    // 绘制棋子文字
    ctx.fillStyle = '#fff';
    ctx.font = `bold ${PIECE_RADIUS}px KaiTi, STKaiti, serif`;
    ctx.textAlign = 'center';
    ctx.textBaseline = 'middle';
    ctx.fillText(PIECES[type], x, y);
}

function handleCanvasClick(event) {
    if (gameState.gameOver) return;
    
    const canvas = document.getElementById('chessboard');
    const rect = canvas.getBoundingClientRect();
    const x = event.clientX - rect.left;
    const y = event.clientY - rect.top;
    
    // 计算点击的网格坐标
    const col = Math.round((x - 25) / GRID_SIZE);
    const row = Math.round((y - 25) / GRID_SIZE);
    
    // 确保在棋盘范围内
    if (row < 0 || row >= 10 || col < 0 || col >= 9) return;
    
    const piece = gameState.board[row][col];
    
    // 如果没有选中的棋子
    if (!gameState.selectedPiece) {
        // 如果点击位置有棋子，并且是当前玩家的棋子
        if (piece && ((gameState.currentPlayer === 'w' && piece.color === RED) || 
                     (gameState.currentPlayer === 'b' && piece.color === BLACK))) {
            gameState.selectedPiece = { row, col, type: piece.type };
            drawBoard();
        }
    } 
    // 如果已经有选中的棋子
    else {
        const { row: fromRow, col: fromCol, type } = gameState.selectedPiece;
        
        // 如果点击的是同一个位置，取消选中
        if (fromRow === row && fromCol === col) {
            gameState.selectedPiece = null;
            drawBoard();
            return;
        }
        
        // 尝试移动棋子（这里省略了合法移动检查）
        // 在实际应用中，这里需要添加移动规则检查
        
        // 记录移动
        const move = {
            from: { row: fromRow, col: fromCol },
            to: { row, col },
            piece: type,
            captured: piece ? piece.type : null
        };
        
        // 执行移动
        gameState.board[row][col] = gameState.board[fromRow][fromCol];
        gameState.board[fromRow][fromCol] = null;
        
        // 更新游戏状态
        gameState.selectedPiece = null;
        gameState.currentPlayer = gameState.currentPlayer === 'w' ? 'b' : 'w';
        gameState.moveHistory.push(move);
        
        // 更新显示
        drawBoard();
        updateStatusDisplay();
        addMoveToHistory(move);
        updateFenDisplay();
        
        // 检查游戏是否结束（这里省略）
        
        // 如果是AI的回合，请求AI移动
        if (!gameState.gameOver && gameState.currentPlayer === 'b') {
            setTimeout(requestAIMove, 500);
        }
    }
}

function requestAIMove() {
    if (gameState.gameOver) return;
    
    const difficulty = parseInt(document.getElementById('difficulty').value);
    
    // 显示AI思考中
    document.getElementById('game-status').textContent = 'AI思考中...';
    
    // 获取当前FEN
    const currentFen = generateFen();
    
    // 向服务器发送请求获取AI移动
    fetch('/get_move', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({ 
            fen: currentFen,
            difficulty: difficulty
        })
    })
    .then(response => response.json())
    .then(data => {
        if (data.move) {
            // 解析AI移动
            const move = parseUciMove(data.move);
            
            if (move) {
                // 执行AI移动
                console.log('move',move)
                executeMove(move);
            } else {
                document.getElementById('game-status').textContent = 'AI移动解析失败';
            }
        } else {
            document.getElementById('game-status').textContent = '获取AI移动失败: ' + (data.error || '未知错误');
        }
    })
    .catch(error => {
        console.error('Error:', error);
        document.getElementById('game-status').textContent = '请求AI移动失败';
    });
}

function parseUciMove(uci) {
    if (uci.length < 4) return null;
    
    const fromCol = uci.charCodeAt(0) - 97;
    const fromRow = 9 - (uci.charCodeAt(1) - 49);
    const toCol = uci.charCodeAt(2) - 97;
    const toRow = 9 - (uci.charCodeAt(3) - 49);
    
    return {
        from: { row: fromRow-1, col: fromCol },
        to: { row: toRow-1, col: toCol }
    };
}

function executeMove(move) {
    const { from, to } = move;
    
    // 记录移动
    const piece = gameState.board[from.row][from.col];
    const captured = gameState.board[to.row][to.col];
    
    const moveRecord = {
        from: { row: from.row, col: from.col },
        to: { row: to.row, col: to.col },
        piece: piece.type,
        captured: captured ? captured.type : null
    };
    
    // 执行移动
    gameState.board[to.row][to.col] = piece;
    gameState.board[from.row][from.col] = null;
    
    // 更新游戏状态
    gameState.currentPlayer = 'w'; // 切换回玩家
    gameState.moveHistory.push(moveRecord);
    
    // 更新显示
    drawBoard();
    updateStatusDisplay();
    addMoveToHistory(moveRecord);
    updateFenDisplay();
    
    // 检查游戏是否结束
    // 省略...
}

function undoMove() {
    if (gameState.moveHistory.length < 1) return;
    
    const lastMove = gameState.moveHistory.pop();
    
    // 撤销移动
    gameState.board[lastMove.from.row][lastMove.from.col] = {
        type: lastMove.piece,
        color: gameState.currentPlayer === 'w' ? BLACK : RED
    };
    
    gameState.board[lastMove.to.row][lastMove.to.col] = lastMove.captured ? {
        type: lastMove.captured,
        color: lastMove.captured === lastMove.captured.toUpperCase() ? RED : BLACK
    } : null;
    
    // 切换玩家
    gameState.currentPlayer = gameState.currentPlayer === 'w' ? 'b' : 'w';
    
    // 更新显示
    drawBoard();
    updateStatusDisplay();
    removeLastMoveFromHistory();
    updateFenDisplay();
}

function generateFen() {
    let fen = '';
    
    for (let row = 0; row < 10; row++) {
        let emptyCount = 0;
        let rowFen = '';
        
        for (let col = 0; col < 9; col++) {
            const piece = gameState.board[row][col];
            if (piece) {
                if (emptyCount > 0) {
                    rowFen += emptyCount;
                    emptyCount = 0;
                }
                rowFen += piece.type;
            } else {
                emptyCount++;
            }
        }
        
        if (emptyCount > 0) {
            rowFen += emptyCount;
        }
        
        fen += rowFen + (row < 9 ? '/' : '');
    }
    
    // 添加其他信息
    fen += ` ${gameState.currentPlayer} - - 0 ${gameState.moveHistory.length + 1}`;
    
    return fen;
}

function updateFenDisplay() {
    document.getElementById('fen-string').value = gameState.fen = generateFen();
}

function updateGameDisplay() {
    drawBoard();
    updateStatusDisplay();
}

function updateStatusDisplay() {
    const statusElement = document.getElementById('game-status');
    
    if (gameState.gameOver) {
        statusElement.textContent = '游戏结束';
    } else {
        statusElement.textContent = gameState.currentPlayer === 'w' ? 
            '红方回合 (玩家)' : '黑方回合 (AI)';
    }
}

function addMoveToHistory(move) {
    const moveList = document.getElementById('move-list');
    const moveNum = Math.ceil(gameState.moveHistory.length / 2);
    const isRedMove = gameState.moveHistory.length % 2 === 1;
    
    if (isRedMove) {
        const moveElement = document.createElement('div');
        moveElement.textContent = `${moveNum}. ${getMoveNotation(move)}`;
        moveList.appendChild(moveElement);
    } else {
        const lastElement = moveList.lastChild;
        if (lastElement) {
            lastElement.textContent += ` ${getMoveNotation(move)}`;
        }
    }
    
    moveList.scrollTop = moveList.scrollHeight;
}

function removeLastMoveFromHistory() {
    const moveList = document.getElementById('move-list');
    const moveNum = Math.ceil(gameState.moveHistory.length / 2);
    
    if (gameState.moveHistory.length === 0) {
        moveList.innerHTML = '';
    } else if (gameState.moveHistory.length % 2 === 1) {
        // 删除最后一步（红方）
        moveList.removeChild(moveList.lastChild);
    } else {
        // 更新最后一条记录（删除黑方移动）
        const lastElement = moveList.lastChild;
        if (lastElement) {
            lastElement.textContent = lastElement.textContent.replace(/\s+\S+$/, '');
        }
    }
}

function getMoveNotation(move) {
    // 简化版移动表示法
    const piece = PIECES[move.piece];
    const from = String.fromCharCode(97 + move.from.col) + (9 - move.from.row);
    const to = String.fromCharCode(97 + move.to.col) + (9 - move.to.row);
    
    return `${piece}${from}-${to}`;
}
